import type { App } from "vue";
const { VITE_PUBLIC_PATH } = import.meta.env;

let config: object = {};

// 设置配置
export const setConfig = (newConfig?: unknown) => {
  config = Object.assign(config, newConfig);
};

// 获取配置
export const getConfig = (key?: string): Configs => {
  if (typeof key === "string") {
    const arr = key.split(".");
    if (arr && arr.length) {
      let data = config;
      arr.forEach((v) => {
        if (data && typeof data[v] !== "undefined") {
          data = data[v];
        } else {
          data = null;
        }
      });
      return data;
    }
  }
  return config;
};
// 获取全局配置
export const getGlobalConfig = async (app: App): Promise<undefined> => {
  app.config.globalProperties.$config = getConfig();
  try {
    const response = await fetch(`${VITE_PUBLIC_PATH}config.json`);
    const config = await response.json();
    let $config = app.config.globalProperties.$config;
    // 自动注入系统配置
    if (app && $config && typeof config === "object") {
      $config = Object.assign($config, config);
      app.config.globalProperties.$config = $config;
      // 设置全局配置
      setConfig($config);
    }
    return $config;
  } catch (_error) {
    throw "请在public文件夹下添加config.json配置文件";
  }
};
